package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.AreaListRes;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.utils.LogUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/21.
 */

public class ConstructionListActivity extends BaseActivity {

    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.construction_lv)
    PullToRefreshListView constructionLv;

    private List<AreaListRes.AreaBean> constructionList;
    private int pageIndex = 1;
    private MyAdapter adapter;
    private ConstructionListActivity mActivity;
    private String areaName, areaId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_construction_list);
        ButterKnife.bind(this);
        mActivity = this;
        int level = SPUtil.getInt(mActivity, "level");
        if(level == 1){
            AreaListRes.AreaBean area = (AreaListRes.AreaBean) getIntent().getExtras().get("area");
            areaName = area.getName();
            areaId = area.getId();
        }else if(level == 2){
            areaName = SPUtil.getString(mActivity, "areaName");
            areaId = SPUtil.getString(mActivity, "areaId");
        }

        titleTv.setText(areaName);
        getHKInfo(null);
        getAreaList("加载中…");
        setListener();
        constructionLv.setRefreshing();
    }

    private void getHKInfo(String alert){
//        JSONObject jsonObject = new JSONObject();
//
//        try {
//            jsonObject.put("areaId", areaId);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("areaId", areaId);
//        params.addHeader("Content-type", "application/json");
//        try {
//            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        String uuid = SPUtil.getString(mActivity, "uuid");
        Utils.requestData(alert, mActivity, "/video/queryHikLoginInfoByArea/" + uuid, params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    UserInfo.Video vedio = gson.fromJson(json, UserInfo.Video.class);
                    SPUtil.put(mActivity, "vedio_ip", vedio.getIp());
                    SPUtil.put(mActivity, "vedio_port", vedio.getIp());
                    SPUtil.put(mActivity, "vedio_username", vedio.getIp());
                    SPUtil.put(mActivity, "vedio_password", vedio.getIp());
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    private void getAreaList(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("areaId", areaId);
            jsonObject.put("pageNum", pageIndex + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String uuid = SPUtil.getString(mActivity, "uuid");
        Utils.requestData(alert, mActivity, "/construction/queryAuthConstructionList/" + uuid, params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(constructionLv.isRefreshing()){
                    constructionLv.onRefreshComplete();
                }
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    AreaListRes areaListRes = gson.fromJson(json, AreaListRes.class);
                    if(areaListRes.getValue() != null && areaListRes.getValue().size()>0){
                        progress(areaListRes.getValue());
                    }else{
                        showEmptyView(constructionLv);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(constructionLv.isRefreshing()){
                    constructionLv.onRefreshComplete();
                }
                showEmptyView(constructionLv);
            }
        });
    }

    private void progress(List<AreaListRes.AreaBean> datas){
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(constructionLv);
            }else{
                dismissEmptyView();
            }
            constructionList = datas;
            adapter = new MyAdapter();
            constructionLv.setAdapter(adapter);
            if (datas.size() == Utils.ONCECOUNT) {
                constructionLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            }
        } else {
            constructionList.addAll(datas);
            adapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            constructionLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    private void setListener(){
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        constructionLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SPUtil.put(mActivity, "constructionid", constructionList.get(position-1).getId());
                SPUtil.put(mActivity, "levelName", constructionList.get(position-1).getName());
                Intent intent = new Intent(mActivity, HomeActivity.class);
                startActivity(intent);
            }
        });

        constructionLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getAreaList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getAreaList(null);
            }
        });
    }

    private class MyAdapter extends BaseAdapter {

//        private int select = -1;

//        public AreaListRes.AreaBean getSelect() {
//            if (select == -1) {
//                return null;
//            }
//            return constructionList.get(select);
//        }
//
//        public void setSelect(int select) {
//            this.select = select;
//            notifyDataSetChanged();
//        }

        @Override
        public int getCount() {
            return constructionList.size();
        }

        @Override
        public Object getItem(int position) {
            return constructionList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null || convertView.getTag() == null) {
                convertView = LayoutInflater.from(mActivity)
                        .inflate(R.layout.item_construction, parent, false);
                holder = new ViewHolder();
                holder.container = (LinearLayout)convertView.findViewById(R.id.container);
                holder.construction_tv = (HXTextView)convertView.findViewById(R.id.construction_tv);
                holder.collect_cb = (CheckBox)convertView.findViewById(R.id.collect_cb);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.construction_tv.setText(constructionList.get(position).getName());
//            if(select == position){
//                holder.collect_iv.setImageResource(R.mipmap.collect_on);
//            }else{
//                holder.collect_iv.setImageResource(R.mipmap.collect_un);
//            }
            int type = position%2;
            if(type == 0){
                holder.container.setBackgroundResource(R.color.color_item_bg);
            }else if(type ==1){
                holder.container.setBackgroundResource(R.color.white_ffffff);
            }
            holder.collect_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                }
            });
            return convertView;
        }

        private class ViewHolder{
            LinearLayout container;
            HXTextView construction_tv;
            CheckBox collect_cb;
        }
    }
}
